package cool.tsy.emos.wx.config.shiro;

import cool.tsy.emos.wx.db.pojo.TbUser;
import cool.tsy.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author: hongxuan.wang
 * @date: Created in 2021/9/25 21:35
 * @description: 实现 shiro 的认证和授权方法
 * @mail: 1443424326@qq.com
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    /**
     * 只支持自己实现的令牌的封装对象
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权（验证权限时调用）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
        int userId = user.getId();
        // 用户权限列表
        Set<String> permissions = userService.searchUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证（登录时调用）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 从令牌中获取 userId，然后检测该账户是否被冻结
        String token = (String) authenticationToken.getPrincipal();
        int userId = jwtUtil.getUserId(token);
        // 查询用户信息
        TbUser user = userService.searchById(userId);
        if (user == null) throw new LockedAccountException("账号已被锁定,请联系管理员");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, getName());
        return info;
    }

}
